//Copyright (c) 2007 Andrew Badera andrew@badera.us
//SVN repository at http://powncenet.googlecode.com/svn/

//Permission is hereby granted, free of charge, to any person
//obtaining a copy of this software and associated documentation
//files (the "Software"), to deal in the Software without
//restriction, including without limitation the rights to use,
//copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the
//Software is furnished to do so, subject to the following
//conditions:

//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//OTHER DEALINGS IN THE SOFTWARE.


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

using BadException;

namespace BadWeb
{
    public class Post
    {
        public static string USER_AGENT = "PownceNET/0.1 +http://code.google.com/p/powncenet/";
        //private const string USER_AGENT = "MyTestPownceClient/0.1 +http://code.google.com/p/powncenet/";

        public static string DoPost(string url, List<HttpVar> vars, string contentType)
        {
            return DoPost(url, vars, new List<HttpHeader>(), contentType, string.Empty, string.Empty, string.Empty);
        }

        public static string DoPost(string url, List<HttpVar> vars, List<HttpHeader> headers, string contentType)
        {
            return DoPost(url, vars, headers, contentType, string.Empty, string.Empty, string.Empty);
        }

        public static string DoPost(string url, List<HttpVar> vars, List<HttpHeader> headers, string contentType, string username, string password)
        {
            return DoPost(url, vars, headers, contentType, username, password, string.Empty);
        }

        public static string DoPost(string url, List<HttpVar> vars, List<HttpHeader> headers, string contentType, string username, string password, string sessionID)
        {
            string responseString = string.Empty;
            string data = string.Empty;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            if (!string.IsNullOrEmpty(username))
            {
                CredentialCache credCache = new CredentialCache();
                credCache.Add(new Uri(url), "Basic", //need to add variable
                          new NetworkCredential(username, password));

                request.Credentials = credCache;
            }

            request.Method = "POST";
            request.ContentType = contentType;
            request.UserAgent = USER_AGENT;
            request.ProtocolVersion = new System.Version("1.0");

            if (string.Empty != sessionID)
            {
                request.Headers.Add(HttpRequestHeader.Cookie, sessionID);
            }
           
            if (headers.Count > 0)
            {
                for (int n = 0; n < headers.Count; n++)
                {
                    HttpHeader thisHeader = headers[n];

                    request.Headers.Add(thisHeader.Key, thisHeader.Value);
                }
            }
              
            data = HttpVar.GetVars(vars);

            byte[] bytes = Encoding.UTF8.GetBytes(data);

            request.ContentLength = bytes.Length;

            try
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            responseString = reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BadLogger.WriteToLog("Post.DoPost", ex, ExceptionEnums.LogEntryType.Error);
                
                throw ex;
            }

            return responseString;
        }     
    }
}
